package com.lagou.rocket.demo.seckill.service.Impl;

import com.lagou.rocket.demo.seckill.service.IInventoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * <p>
 *
 * </p>
 *
 * @author KK
 * @since 2021-11-06
 */
@Slf4j
@Service
public class InventoryServiceImpl implements IInventoryService {

    private final RedisTemplate redisTemplate;

    // 库存预检查key的前缀
    private final static String PREFIX = "inventory_";

    public InventoryServiceImpl(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }


    @Override
    public boolean preCheckInventory(String productId) {

        String inventoryKey = PREFIX + productId;
        int inventory = Integer.parseInt((String) Objects.requireNonNull(redisTemplate.opsForValue().get(inventoryKey))) ;

        log.info("预检查库存， 当前redis库存为：{}", inventory);

        return inventory > 0;
    }
}
